package com.gwz.shelf.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gwz.shelf.entity.auth.bo.Modules;
import com.gwz.shelf.entity.auth.bo.RoleModules;
import com.gwz.shelf.mapper.auth.ModulesMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 模块表 服务实现类
 * </p>
 *
 * @author 时间
 * @since 2021-04-25
 */
@Service
public class ModulesService extends ServiceImpl<ModulesMapper, Modules> implements IService<Modules> {
    @Autowired
    private RolesService rolesService;
    @Autowired
    private RoleModulesService roleModulesService;

    /**
     * @return
     */
    public List<Tree<String>> getModulesByUserId(String userId) {
        List<String> roleIds = rolesService.getByUserId(userId);
        List<String> moduleIds = roleModulesService
                .lambdaQuery()
                .in(RoleModules::getRoleId, roleIds)
                .list()
                .stream()
                .map(RoleModules::getModuleId)
                .collect(Collectors.toList());
        List<Modules> modules = lambdaQuery().in(Modules::getId, moduleIds).list();

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
            // 最大递归深度
        treeNodeConfig. setDeep(3);


        List<Tree<String>> treeNodes = TreeUtil.build(modules, "", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId());

                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("path", treeNode.getPath());
                    tree.putExtra("iconClass", treeNode.getIconClass());
                    tree.putExtra("createTime", treeNode.getCreateTime());
                    tree.putExtra("updateTime", treeNode.getUpdateTime());
                });
        return treeNodes;
    }

}
